// Helper.js
// ====================

var fs = require('fs');
var config = require('./configController');
var logger = require('./logger');

module.exports = {
	/* tries to change the uid of the current process - exits otherwise */
	setUser: function(uid) {

		var cuid = process.getuid();
	
		if (cuid != uid) {
		
			logger.debug('We are running as User '+cuid+' but we should be '+uid+' -> trying to change');
	
			try {
				process.setuid(uid);
				logger.debug('Successfully changed UID to ' + process.getuid());
				return true;
			}
			catch (err) {
				logger.error('Failed to set UID to '+uid+': ' + err);
				return false;
			}
		}
		
		return true;
	},
	/* checks the arguments and tries to get the source file path */
	checkArgsAndGetSource: function() {
		
		var argv = process.argv;
		
		if (argv.length!=3) {
			logger.error('Invalid argument count '+argv.length);
			logger.error('Usage: '+argv[1]+' <source>');
			return undefined;
		}
		
		return argv[argv.length-1];
	},
	/* tries to get the source file extension - exits otherwise */
	getFileType: function(path) {
	
		var start = path.lastIndexOf('.');
		if (start==-1) {
			logger.error('Couldn\'t find . in path '+path);
			return undefined;
		}
		
		return path.substring(start+1,path.lenth).toLowerCase();
	},
	/* checks if a file exists and is accissable */
	fileExists: function(path) {
		try {
			var stat = fs.statSync(path);
			return true;
		}
		catch (err) {
			return false;
		}
	},
	/* generates a random hash */
	getHash: function() {

		var hash = require('crypto').randomBytes(2);
		hash = new Date().getTime()+"_"+hash.toString('hex');
		
		return hash;
	},
	/* replaces given %placeholders% with given strings*/
	replaceStrings: function(str,data) {
		
		Object.keys(data).forEach(function(k) {
			var v = data[k];
			
			str=str.replace('%'+k+'%',v)
		});
		
		return str;
	}
};
